import {
  AlipayCircleOutlined,
  AlipayOutlined,
  LockOutlined,
  MobileOutlined, TaobaoCircleOutlined,
  TaobaoOutlined,
  UserOutlined, WeiboCircleOutlined,
  WeiboOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {Button, Divider, Space, Tabs, message, theme, Alert} from 'antd';
import type { CSSProperties } from 'react';
import { useState } from 'react';
import TuiZi from '@/pages/LoginPage/resource/TuiZi.png'
import DisplayBackground from '@/pages/LoginPage/resource/Test1.mp4'
import Footer from "@/components/Footer/index"
import {login} from "@/services/ant-design-pro/api";
import {history} from "@@/core/history";
import {flushSync} from "react-dom";
import React from "react/index";
import {FormattedMessage, SelectLang, useIntl, useModel} from "@@/exports";
import {userIdentify} from '@/services/list'

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

import { PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormSelect,
} from '@ant-design/pro-components';
import { Form } from 'antd';

type LoginType = 'phone' | 'account';
// import { PictureRecycles } from '@/components';
const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};


const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Page: React.FC = () => {
  const [form] = Form.useForm<{ name: string; company: string }>();

  const customTitleStyle = {
    fontSize: '27px', // 这里设置你想要的字号大小
  };
  const [loginType, setLoginType] = useState<API.LoginResult>('account')
  const { token } = theme.useToken();

  const [userLoginStateIndex, setuserLoginStateIndex] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values, type });
      if (msg.status === 'ok') {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }else{
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.failure',
          defaultMessage: '登录失败！',
        });
        message.error(defaultLoginSuccessMessage);
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setuserLoginStateIndex(msg);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  const { status, type: loginTypeIndexindex } = userLoginStateIndex;


  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        logo={TuiZi}
        backgroundVideoUrl={DisplayBackground}
        title={<div style={{ fontSize: '24px' }}>通用软件服务产品销售及结算系统</div>}
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        subTitle="最好用的服务产品销售及结算系统！"
        activityConfig={{
          style: {
            boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
            color: token.colorTextHeading,
            borderRadius: 8,
            backgroundColor: 'rgba(255,255,255,0.25)',
            backdropFilter: 'blur(4px)',
          },
          title: 'V1.1.1.A',
          subTitle: '内部测试系统，具体详情查看',
          action: (
            <Button
              size="large"
              style={{
                borderRadius: 15,
                background: token.colorBgElevated,
                color: token.colorPrimary,
                width: 100,
              }}
            >
              去看看
            </Button>
          ),
        }}
        actions={
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'column',
            }}
          >
            <Divider plain>
              <span
                style={{
                  color: token.colorTextPlaceholder,
                  fontWeight: 'normal',
                  fontSize: 14,
                }}
              >
                其他登录方式
              </span>

            </Divider>
            <Space align="center" size={24}>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                  height: 40,
                  width: 40,
                  border: '1px solid ' + token.colorPrimaryBorder,
                  borderRadius: '50%',
                }}
              >
                <AlipayOutlined style={{ ...iconStyles, color: '#1677FF' }} />
              </div>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                  height: 40,
                  width: 40,
                  border: '1px solid ' + token.colorPrimaryBorder,
                  borderRadius: '50%',
                }}
              >
                <TaobaoOutlined style={{ ...iconStyles, color: '#FF6A10' }} />
              </div>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                  height: 40,
                  width: 40,
                  border: '1px solid ' + token.colorPrimaryBorder,
                  borderRadius: '50%',
                }}
              >
                <WeiboOutlined style={{ ...iconStyles, color: '#1890ff' }} />
              </div>
            </Space>
            <Footer/>
          </div>
        }

        onFinish={async (values) => {
          console.log(123123)
          await handleSubmit(values as API.LoginParams);
        }}
      >
        <Tabs
          centered
          activeKey={loginType}
          onChange={(activeKey) => setLoginType(activeKey as LoginType)}
        >

          <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
          <Tabs.TabPane key={'phone'} tab={'手机号登录'} />
        </Tabs>
        {loginType === 'account' && (
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: (
                  <UserOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'用户名: admin or user'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'密码: ant.design'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
        )}
        {loginType === 'phone' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: (
                  <MobileOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              name="mobile"
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              captchaProps={{
                size: 'large',
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`;
                }
                return '获取验证码';
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              onGetCaptcha={async () => {
                message.success('获取验证码成功！验证码为：1234');
              }}
            />
          </>
        )}
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>


          <a
            style={{
              float: 'right',
            }}
          >
            忘记密码
          </a>
          <ModalForm
            <{

              name: string;
              company: string;
            }>
            width={380}

            title={<div style={{ fontSize: '30px' }}>注册表单</div>}
            trigger={
              <a type="primary" style={{
                float: 'right',
                marginRight:'20px',
              }}>
                <PlusOutlined />
                去注册
              </a>
            }
            form={form}
            autoFocusFirstInput
            modalProps={{
              destroyOnClose: true,
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              await waitTime(1700);
              console.log(values.name);
              message.success('提交成功');
              return true;
            }}
          >
            <ProForm.Group>
              <ProFormText
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.register.nickname.required"
                        defaultMessage="请输入账户昵称"
                      />
                    ),
                  },
                ]}
                width="md"
                name="name"
                label="昵称"
                tooltip="最长为10位英文字母与数字混合"
                placeholder="请输入昵称"
              />

            </ProForm.Group>
            <ProForm.Group>
              <ProFormText
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.register.account.required"
                        defaultMessage="请输入账号"
                      />
                    ),
                  },
                ]}
                width="md"
                name="account"
                label="账号"
                tooltip="最长为10位数字"
                placeholder="请输入账号"
              />

            </ProForm.Group>
            <ProForm.Group>
              <ProFormSelect
                options={[
                  {
                    value: 'yes',
                    label: '是',
                  },
                  {
                    value: 'no',
                    label: '否',
                  }
                ]}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.item.name.required"
                        defaultMessage="请输入商品名称！"
                      />
                    ),
                  },
                ]}
                width="xs"
                name="useMode"
                label="是否为管理员"
              />

            </ProForm.Group>
            <ProFormText
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.register.password.required"
                      defaultMessage="请填入密码"
                    />
                  ),
                },
                {
                  pattern: /^\d+$/,
                  message: '密码只能包含数字',
                },
              ]}
              width="sm"
              name="password"
              label="输入密码"
            />
            <ProFormText
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.register.confirmPassword.required"
                      defaultMessage="请再次输入密码"
                    />
                  ),
                },
                {
                  pattern: /^\d+$/,
                  message: '密码只能包含数字',
                },
                ({
                   getFieldValue,
                 }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码必须相同!'));
                  },
                }),
              ]}
              width="sm"
              name="confirmPassword"
              label="请确认密码"
            />
          </ModalForm>


        </div>
      </LoginFormPage>

    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <Page/>
    </ProConfigProvider>
  );
};
